package cmd

import (
	"context"
	"net/http"
)

func Run(ctx context.Context) error {
	//os.Setenv("METABANK_IDC_NAME", "idc1")
	//os.Setenv("NAMESPACE", "default")
	//os.Setenv("KUBERNETES_SERVICE_HOST", "10.247.0.1")
	//os.Setenv("KUBERNETES_SERVICE_PORT", "443")

	ictx, cancelFunc := context.WithCancel(context.TODO())
	errCh := make(chan error)
	defer close(errCh)

	s := NewServerRunOptions()
	go func() {
		if err := run(s, ictx); err != nil {
			errCh <- err
		}
	}()

	for {
		select {
		case <-ctx.Done():
			cancelFunc()
			return nil
		case err := <-errCh:
			cancelFunc()
			return err
		}
	}
}

func run(s *ServerRunOptions, ctx context.Context) error {

	apiserver, err := s.NewAPIServer()
	if err != nil {
		return err
	}

	err = apiserver.PrepareRun()
	if err != nil {
		return err
	}

	err = apiserver.Run(ctx)
	if err == http.ErrServerClosed {
		return nil
	}
	return err

}
